package hzn.controller;

import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import hzn.entity.Dept;
import hzn.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
public class DeptController_Provider {
    int num;
    @Autowired
    DeptService service;

    @Autowired
    DiscoveryClient client;
    @GetMapping("/dept/discover")
    public Object discover(){
        List<String>list=client.getServices();
        System.out.println("***********服务发现**********"+list);
        List<ServiceInstance>srvList=client.getInstances("PROVIDER-DEPT");
        for(ServiceInstance e:srvList){
            System.out.println(e.getServiceId()+"\t"+e.getHost()+"\t"+e.getPort()+"\t"+e.getUri());
        }
        return client;
    }
    @PostMapping("/dept/add")
    //必须给参数添加RequestBody注解，用于从http请求体中提取数据
    public boolean add(@RequestBody Dept dept){
        return service.add(dept);
    }

    @GetMapping("/dept/get/{id}")
    @HystrixCommand(fallbackMethod = "hystrix_get")
    //@HystrixCommand
    public Dept get(@PathVariable Integer id){
        System.out.println("provider03--num:"+num++);
        Dept d=service.get(id);
        if(null==d){
            throw new RuntimeException("查询不到id为:"+id+"的信息");
        }
        return d;
    }
    Dept hystrix_get(@PathVariable("id") Integer id){
        return new Dept().setDname("nobody").setDb_source("nodb");
    }

    @GetMapping("/dept/list")
    public List<Dept> getAll(){
        System.out.println(Thread.currentThread().getName());
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {}
        System.out.println("provider01--num:"+num++);
        return service.list();
    }
}
